<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-23 17:35:06
 * @LastEditTime : 2020-02-20 16:14:20
 * @LastEditors  : Please set LastEditors
-->
<template>
    <div>
        <h3>
            虚拟机列表 <span v-if="accessName" class="access-name">接入机器：{{ accessName }}</span>
        </h3>
        <div class="headerBtn1">
            <!--<Button type="primary"  ghost style="position:relative;z-index:55" @click="opeartionManyVm">批量操作虚拟机</Button>-->
            <Select filterable
                v-model="virtualSystypeOfReach"
                filterable
                style="width:150px;"
                clearable
                placeholder="请选择操作系统类型"
                @on-change="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
            >
                <Option value="linux">Linux</Option>
                <Option value="windows">Windows</Option>
                <!-- <Option value="mac">Mac</Option> -->
                <Option value="unix">Unix</Option>
            </Select>
            <Select filterable
                v-model="virtualvmTypeOfReach"
                filterable
                style="width:150px;margin-left:15px;"
                clearable
                placeholder="请选择虚拟机类型"
                @on-change="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
            >
                <Option value="VM">VM</Option>
                <Option value="SERVER">SERVER</Option>
                <Option value="CLIENT">CLIENT</Option>
                <Option value="DRT">DRT</Option>
                <Option value="IDS">IDS</Option>
                <Option value="DES">DES</Option>
                <Option value="WAF">WAF</Option>
                <Option value="FW">FIREWALL</Option>
                <Option value="PRT">PRT</Option>
            </Select>
            <!--<Select filterable v-model="virtualNetworkIdOfReach" filterable  style="width:150px;margin-left:15px;" clearable placeholder="请选择子网络"  @on-open-change="reachNetworkList"  @on-change="vmCurrentPage=1;getVmListManage()">
            <Option v-for="(item,index) in networkData" :key="index" :value="item.networkId">{{item.networkName}}</Option>
        </Select>-->
            <Input
                placeholder="请输入虚拟机名称"
                v-model="virtualNameOfReach"
                @on-change="
                    vmCurrentPage = 1;
                    limitingReach();
                "
                clearable
                style="width:180px;margin-left:15px;position:relative;z-index:55"
                v-show="controlSearchBtn"
            />
            <Input
                placeholder="请输入IP"
                v-model="virtualIPOfReach"
                @on-change="
                    vmCurrentPage = 1;
                    limitingReach();
                "
                clearable
                style="width:180px;margin-left:15px;position:relative;z-index:55"
                v-show="controlSearchBtn"
            />
            <Input
                placeholder="请输入镜像名称"
                v-model="virtualImageNameOfReach"
                @on-change="
                    vmCurrentPage = 1;
                    limitingReach();
                "
                clearable
                style="width:180px;margin-left:15px;position:relative;z-index:55"
                v-show="controlSearchBtn"
            />
            <Button
                type="dashed"
                @click="controlSearch"
                style="margin-left:15px;"
                :icon="controlSearchImage"
                >{{ controlSearchText }}</Button
            >
            <span style="color:#f90;float:right;"
                ><Icon
                    type="ios-information-circle"
                    style="color:f90"
                />关机后才能生成镜像,docker不支持生成镜像</span
            >
        </div>
        <TableList
            ref="selection"
            :columns="vmColumnsData"
            :data="vmListDataTable"
            :page.sync="vmCurrentPage"
            :size.sync="vmItemPage"
            :height="tableHeight"
            :total="vmTotal"
            :loading="loadingTable"
            :showDef="false"
            @change-page="switchineVmCurrentPage"
            @change-size="switchVmItemPage"
        ></TableList>
        <!-- 虚拟机元数据 -->
        <Modal
            v-model="vmMetadata"
            title="元数据"
            ok-canel="关闭"
            ok-text="保存"
            :loading="vmMetadataLoading"
            @on-cancel="cancel"
            @on-ok="SaveMetaData"
        >
            <Tag type="dot" color="primary">虚拟机：{{ vmName }}</Tag>
            <div
                v-for="(item, key) in metadataData"
                :key="key"
                style="margin:5px 0px;text-align:left;position:relative;width:101%"
            >
                <Input
                    placeholder="Enter key"
                    style="width: 226px"
                    v-model="item.key"
                    clearable
                ></Input>
                <Icon type="md-remove" />
                <Input
                    placeholder="Enter value"
                    style="width: 220px"
                    v-model="item.value"
                    clearable
                ></Input>
                <Icon
                    type="md-remove-circle"
                    @click="removeMetadata(key)"
                    :size="20"
                    style="cursor:pointer"
                />
            </div>
            <div>
                <Button icon="ios-add" type="dashed" size="large" @click="handleAddMetadata"
                    >创建Metadata</Button
                >
            </div>
        </Modal>
        <!-- 批量操作虚拟机面板 -->
        <Modal v-model="vmManyPanel" width="371">
            <p slot="header" style="text-align:left">
                <span>共选择了{{ vmManyNumber }}台虚拟机</span>
            </p>
            <div>
                <div>
                    <Poptip
                        v-for="(item, index) in btnData"
                        :key="index"
                        confirm
                        title="您确定要执行此操作吗?"
                        @on-ok="okVm(item)"
                        @on-cancel="cancel"
                    >
                        <Button type="primary" ghost style="margin:5px;">{{ item }}</Button>
                    </Poptip>
                </div>
            </div>
            <div slot="footer">
                <Button type="primary" @click="vmManyPanel = false">关闭</Button>
            </div>
        </Modal>
        <!-- 端口转发列表 -->
        <Modal v-model="portListPanel" width="1200">
            <p slot="header" style="font-size:14px;text-align:left">
                <!-- <Icon type="ios-information-circle"></Icon> -->
                <span>虚拟机：{{ vmName }}</span>
            </p>
            <div style="text-align:center">
                <div style="text-align:left;margin-bottom:10px">
                    <Button type="primary" style="margin:5px;" @click="openPortPanel"
                        >开放端口</Button
                    >
                </div>
                <Table
                    border
                    ref="selection"
                    :columns="portTableCloums"
                    :data="portTableData"
                    :stripe="true"
                    :show-header="true"
                ></Table>
            </div>
            <div slot="footer">
                <Button type="primary" @click="portListPanel = false">关闭</Button>
            </div>
        </Modal>
        <!-- 转发端口 -->
        <Modal
            v-model="openPort"
            title="创建"
            ok-canel="关闭"
            ok-text="保存"
            width="380"
            :loading="addPortLoading"
            @on-cancel="cancel"
            @on-ok="addPort"
        >
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="类型" prop="type">
                    <RadioGroup v-model="formValidate.type" @on-change="listenTypeChange">
                        <Radio label="ssh"></Radio>
                        <Radio label="rdp"></Radio>
                        <Radio label="vnc">vnc</Radio>
                        <Radio label="other"></Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="other" prop="customType" v-if="disabledType">
                    <Input
                        v-model="formValidate.customType"
                        style="width:200px"
                        placeholder="请输入其他类型"
                    ></Input>
                </FormItem>
                <FormItem label="端口" prop="port">
                    <!-- <Input  type="number" min="1"  max="65535"  ></Input> -->
                    <input-number
                        :min="1"
                        :value="1"
                        :max="65534"
                        v-model="formValidate.port"
                        style="width:200px"
                    ></input-number>
                </FormItem>
                <FormItem label="协议" prop="protocol">
                    <RadioGroup v-model="formValidate.protocol">
                        <Radio label="tcp">TCP</Radio>
                        <Radio label="udp" :disabled="disabledprototol">UDP</Radio>
                        <Radio label="icmp" :disabled="disabledprototol">ICMP</Radio>
                        <!-- <Radio label="all" :disabled="disabledprototol">ALL</Radio> -->
                    </RadioGroup>
                </FormItem>
            </Form>
            <!-- <Label>端口：</Label>
        <Input type="number"/>
        <Label>类型：</Label>
        <Select filterable>
            <Option>ssh</Option>
            <Option>rdp</Option>
            <Option>vnc</Option>
            <Option>console</Option>
        </Select> -->
        </Modal>
        <!-- 接入选择页面 -->
        <Modal
            v-model="selectDataPanel"
            title="选择接入的IP"
            ok-canel="关闭"
            ok-text="接入"
            width="380"
            :loading="selectDataPanelLoading"
            @on-cancel="cancel"
            @on-ok="vmAccessChage"
        >
            <div>
                <RadioGroup
                    v-model="accessVmIp"
                    v-for="(item, index) in selectDataGroup"
                    :key="index"
                    @on-change="changeIpAccess"
                >
                    <Radio :label="item.ip">{{ item.ip }}</Radio>
                </RadioGroup>
            </div>
        </Modal>
        <!-- 页面loading -->
        <Spin fix v-show="isSpinShow">
            <Icon type="load-c" size="30" class="demo-spin-icon-load"></Icon>
            <div>Loading...</div>
        </Spin>
        <!--编辑密码-->
        <Modal
            v-model="passwordModal.show"
            title="编辑密码"
            width="380"
            :loading="passwordModal.loading"
            @on-cancel="cancel"
            @on-ok="changePassword"
        >
            <div>
                密码：<Input
                    v-model="vmPassword"
                    style="width:200px"
                    placeholder="请输入密码"
                ></Input>
            </div>
        </Modal>
        <Modal
            v-model="vmOpModal.show"
            title="操作虚拟机"
            width="380"
            @on-cancel="cancel"
            @on-ok="vmSwitchTypeOp"
        >
            <div style="font-size:14px;">
                {{ vmOpModal.content }}
            </div>
        </Modal>
        <Modal
            v-model="createImageModal.show"
            title="生成镜像"
            width="380"
            @on-cancel="cancel"
            @on-ok="createImage"
        >
            <div style="font-size:14px;">
                确定生成镜像?
            </div>
        </Modal>
    </div>
</template>

<script>
import axios from '@/libs/axios1';
import $ from 'jquery';
import cookieUse from '@/libs/cookie.js';
import { updateCaseAnalyse } from '@/api/event';
export default {
    name: 'vmManagement',
    components: {},
    props: ['prjId', 'caseId', 'templateId', 'caseName', 'accessName'],
    data() {
        return {
            pageItemGroup: [10, 20, 30, 40],
            isSpinShow: false,
            loadingTable: true,
            vmManyPanel: false,
            vmManyNumber: '',
            vmName: '',
            vmMetadata: false,
            vmMetadataLoading: true,
            metadataData: [
                {
                    key: '',
                    value: ''
                }
            ],
            currentProjectId: '',
            projectName: '',
            userName: '',
            vmTotal: 0,
            vmCurrentPage: 1,
            vmItemPage: 10,
            vmColumnsData: [
                {
                    title: '虚拟机名称',
                    key: 'name',
                    minWidth: 100,
                    tooltip: true
                },
                {
                    title: 'IP',
                    key: 'ipAddress',
                    minWidth: 100,
                    tooltip: true,
                    render: (h, params) => {
                        let _this = this;
                        params = params.row;
                        let addresses = [];
                        if (params.addresses) {
                            if (params.addresses.length != 0) {
                                addresses = params.addresses.map((item) => {
                                    //                                          return h('div',{},item.ip);
                                    let ips = item.ips.map((ip) => {
                                        return h('div', {}, ip.ipAddress);
                                    });
                                    return h('div', {}, ips);
                                });
                                return h('div', {}, addresses);
                            }
                        }
                    }
                },
                {
                    title: '用户名',
                    key: 'username',
                    minWidth: 100,
                    tooltip: true,
                    filter: (accesses, data) => {
                        return data.accesses.length > 0 ? data.accesses[0].username : '-';
                    }
                },
                {
                    title: '密码',
                    key: 'password',
                    minWidth: 100,
                    tooltip: true,
                    filter: (accesses, data) => {
                        return data.accesses.length > 0 ? data.accesses[0].password : '-';
                    }
                },
                {
                    title: '接入类型',
                    key: 'accessType',
                    minWidth: 100,
                    tooltip: true,
                    filter: (accesses, data) => {
                        return data.accesses.length > 0
                            ? data.accesses.map((item) => item.accessType).join(',')
                            : '-';
                    }
                },
                {
                    title: '操作系统类型',
                    key: 'sysType',
                    minWidth: 120,
                    tooltip: true
                },
                {
                    title: '镜像名称',
                    key: 'imageName',
                    minWidth: 100,
                    tooltip: true
                },
                {
                    title: '虚拟机状态',
                    key: 'status',
                    minWidth: 100,
                    render: (h, params) => {
                        let _this = this;
                        params = params.row;
                        let statusVm = '',
                            fontColor = '',
                            statusLoading = false,
                            ErrorMesage = '';
                        if (_this.vmGroupStatus.length != 0) {
                            $.each(_this.vmGroupStatus, function(i, element) {
                                if (element.id == params.id) {
                                    if (element.enableCrash) {
                                        statusVm = 'MELT';
                                        ErrorMesage = element.crashMsg;
                                    } else {
                                        statusVm = element.status;
                                        ErrorMesage = '';
                                        // statusVm  =  "MELT";
                                    }
                                    statusLoading = element.loading;
                                    return;
                                }
                            });
                        }
                        let statusVmGroup = {
                            ACTIVE: '运行中/#43CD80/false/alRunning.png',
                            Running: '运行中/#43CD80/false/alRunning.png',
                            SHUTOFF: '已关机/#DB4747/false/alOff.png',
                            DOWN: '已关机/#DB4747/false/alOff.png',
                            Stopped: '已停止/#DB4747/false/alStop.png',
                            SUSPENDED: '已挂起/#DB4747/false/alSuspend.png',
                            ERROR: '运行ERROR/#DB4747/false/runningError.png',
                            PAUSED: '已暂停/#43CD80/false/alPause.png',
                            CRUSH: '运行ERROR/#DB4747/false/runningError.png',
                            UNKNOWN: '运行ERROR/#DB4747/false/runningError.png',
                            'powering-off': '关机中/#57a3f3/true',
                            'powering-on': '启动中/#57a3f3/true',
                            rebuilding: '重置中/#57a3f3/true',
                            rebooting_hard: '重启中/#57a3f3/true',
                            suspending: '挂起中/#57a3f3/true',
                            resuming: '拯救中/#57a3f3/true',
                            pausing: '暂停中/#57a3f3/true',
                            unpausing: '启动中/#57a3f3/true',
                            MELT: '已崩溃/#DB4747/false/runningError.png'
                        };
                        if (!statusVmGroup[statusVm]) {
                            statusVmGroup[statusVm] = '加载中/#808695/true';
                        }
                        let _iamgeName =
                            statusVmGroup[statusVm].split('/')[2] == 'false'
                                ? './static/' + statusVmGroup[statusVm].split('/')[3]
                                : '';
                        return h(
                            'div',
                            {
                                style: {
                                    color: statusVmGroup[statusVm].split('/')[1]
                                }
                            },
                            [
                                h(
                                    'Tag',
                                    {
                                        props: {
                                            color: statusVmGroup[statusVm].split('/')[1]
                                        },
                                        attrs: {
                                            title: ErrorMesage
                                        }
                                    },
                                    statusVmGroup[statusVm].split('/')[0]
                                )
                            ]
                        );
                    }
                },
                {
                    title: '虚拟机类型',
                    key: 'vmType',
                    minWidth: 100,
                    tooltip: true
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 460,
                    opList: [
                        {
                            txt: '生成镜像',
                            tooltip: true,
                            title: '确定生成镜像？',
                            disabled: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    $.each(_this.vmGroupStatus, function(i, element) {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled =
                                    !(statusVm == 'DOWN' || statusVm == 'SHUTOFF') ||
                                    data.vzType == 'docker';
                                return disabled;
                            },
                            fun: (data) => {
                                this.createImage(data);
                                return;
                            }
                        },
                        {
                            txt: '开机',
                            tooltip: true,
                            title: '确认对该虚拟机进行开机操作吗?',
                            disabled: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    $.each(_this.vmGroupStatus, function(i, element) {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = !['SHUTOFF', 'DOWN', 'Stopped'].includes(statusVm);
                                return disabled;
                            },
                            fun: (data) => {
                                this.vmSwitchTypeOp(data.id, '开机');
                                return;
                            }
                        },
                        {
                            txt: '关机',
                            tooltip: true,
                            title: '确认对该虚拟机进行关机操作吗?',
                            disabled: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    $.each(_this.vmGroupStatus, function(i, element) {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = !['Running', 'ACTIVE', 'CRUSH', 'PASSWORD'].includes(
                                    statusVm
                                );
                                return disabled;
                            },
                            fun: (data) => {
                                this.vmSwitchTypeOp(data.id, '关机');
                                return;
                            }
                        },
                        {
                            txt: '重置',
                            tooltip: true,
                            title: '确认对该虚拟机进行重置操作吗',
                            disabled: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    $.each(_this.vmGroupStatus, function(i, element) {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = [
                                    'SUSPENDED',
                                    'ERROR',
                                    'PASSWORD',
                                    'CRUSH',
                                    'PASSWORD'
                                ].includes(statusVm);
                                return disabled;
                            },
                            fun: (data) => {
                                this.vmSwitchTypeOp(data.id, '重置');
                                return;
                            }
                        },
                        {
                            txt: '重启',
                            tooltip: true,
                            title: '确认对该虚拟机进行重启操作吗?',
                            disabled: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    $.each(_this.vmGroupStatus, function(i, element) {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = !['ACTIVE', 'Running', 'CRUSH', 'MELT'].includes(
                                    statusVm
                                );
                                return disabled;
                            },
                            fun: (data) => {
                                this.vmSwitchTypeOp(data.id, '重启');
                                return;
                            }
                        },
                        {
                            txt: '接入虚拟机',
                            dropdown: true,
                            dropdownList: (data) => {
                                return data.accesses.map((access) => {
                                    return {
                                        name: access.accessType,
                                        title: access.accessType
                                    };
                                });
                            },
                            // current: (data) => {
                            //     return {
                            //         name: data.accesses[0].accessType,
                            //         title: data.accesses[0].accessType
                            //     };
                            // },
                            disabled: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    $.each(_this.vmGroupStatus, function(i, element) {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = !['ACTIVE', 'Running'].includes(statusVm);
                                return disabled;
                            },
                            fun: (data, type) => {
                                this.vmAccess(data.id, type || data.accesses[0].accessType);
                            }
                        },
                        {
                            txt: '设为接入机器',
                            fun: (vm) => {
                                //设为接入机器
                                updateCaseAnalyse({
                                    id: this.caseId,
                                    accessName: vm.name
                                })
                                    .then(({ code, message }) => {
                                        if (code !== 1) {
                                            this.$Message.warning(message);
                                            return;
                                        }
                                        this.$Message.info('设置成功');
                                        this.$emit('setAccess', vm.name);
                                    })
                                    .catch(() => {
                                        this.$Message.error('设为接入机器异常');
                                    });
                            }
                        }
                    ]
                }
            ],
            vmListDataTable: [],
            tableHeight: '',
            virtualNameOfReach: '',
            virtualIPOfReach: '',
            virtualSystypeOfReach: '',
            virtualKeyOfReach: '',
            virtualValueOfReach: '',
            virtualvmTypeOfReach: '',
            virtualMacOfReach: '',
            virtualImageNameOfReach: '',
            virtualNetworkIdOfReach: '',
            virtualSegmentIdOfReach: '',
            virtualSubnetIdOfReach: '',
            vmKeys: [],
            vmValues: [],
            vmIdGroupStatus: [],
            vmGroupStatus: [],
            vmPassword: '',
            vmId_: '',
            updatePasswordLoading: true,
            tableListHeight: '',
            selectValue: '',
            vmAttributeData: [],
            selectTableDataGroup: [],
            btnData: [],
            setTimeClear: '',

            portListPanel: false,
            portTableCloums: [
                {
                    title: 'forwardIP',
                    key: 'forwardIp',
                    align: 'left'
                },
                {
                    title: 'forwardPort',
                    key: 'forwardPort',
                    align: 'left'
                },
                // {
                //     title:'vmName',
                //     key:'name',
                //     align:'center'
                // },
                {
                    title: 'vmIP',
                    key: 'vmIp',
                    align: 'left'
                },
                {
                    title: 'vmPort',
                    key: 'vmPort',
                    align: 'left'
                },

                {
                    title: 'type',
                    key: 'type',
                    align: 'left'
                },
                {
                    title: 'protocal',
                    key: 'protocal',
                    align: 'left'
                },
                {
                    title: 'lastExpireTime',
                    key: 'lastExpireTime',
                    align: 'left'
                },
                {
                    title: 'createName',
                    key: 'userName',
                    align: 'left'
                },
                {
                    title: 'actions',
                    key: 'actions',
                    // align:'center',
                    render: (h, params) => {
                        let _this = this;
                        params = params.row;
                        return h(
                            'Poptip',
                            {
                                style: {},
                                props: {
                                    confirm: true,
                                    title: '您确定要删除吗？'
                                },
                                on: {
                                    'on-ok': () => {
                                        _this.deleteVmPort(params.token);
                                    },
                                    'on-cancel': () => {}
                                }
                            },
                            [
                                h(
                                    'Button',
                                    {
                                        style: {
                                            margin: '5px'
                                        },
                                        props: {
                                            type: 'error'
                                        }
                                    },
                                    '删除'
                                )
                            ]
                        );
                    }
                }
            ],
            portTableData: [],
            openPort: false,
            addPortLoading: true,
            formValidate: {
                type: 'ssh',
                port: 22,
                protocol: 'tcp',
                customType: 'customType'
            },
            ruleValidate: {
                type: [{ required: true, message: '请选择类型', trigger: 'blur,change' }],
                port: [
                    {
                        required: true,
                        message: '请填写端口',
                        trigger: 'blur,change',
                        type: 'number'
                    }
                ],
                protocol: [{ required: true, message: '请选择协议', trigger: 'blur,change' }],
                customType: [
                    { required: true, message: '请输入自定义类型', trigger: 'blur,change' }
                ]
            },
            disabledType: false,
            disabledprototol: true,
            accessTokenRef: '',
            setTimeoutReach: '',
            networkData: [],
            subnetData: [],
            segmentsData: [],
            refreshIndex: 0,
            vmNetworkData: [],
            controlSearchBtn: false,
            controlSearchText: '更多',
            controlSearchImage: 'ios-more',
            //接入方式增加选择面板
            selectDataPanel: false,
            selectDataGroup: [],
            selectDataPanelLoading: true,
            accessVmIp: '',
            accessVmId: '',
            accessVmType: '',
            passwordModal: {
                loading: true,
                show: false
            },
            vmOpModal: {
                loading: true,
                show: false,
                content: ''
            },
            createImageModal: {
                loading: true,
                show: false,
                content: ''
            }
        };
    },
    created() {
        this.userName = this.$store.state.user.username; //localStorage.nickName
        this.currentProjectId = this.prjId;
        this.vmCurrentPage = sessionStorage.getItem('vmCurrentPage')
            ? Number(sessionStorage.getItem('vmCurrentPage'))
            : 1;
        this.vmItemPage = sessionStorage.getItem('vmItemPage')
            ? Number(sessionStorage.getItem('vmItemPage'))
            : 10;
        //      this.tableHeight = $(window).height() - 262 ;

        // console.log(this.$refs)
        // this.currentProjectId = 'cd8ced77c2104b8897ad0fd70bfd7dff';
        this.getVmListManage();
        // this.getVmAttributeKey();
        //this.getProjectInformation()
        // console.log(this.getRandomPassword(6))
    },
    methods: {
        changeIpAccess(value) {
            console.log(value);
            this.accessVmIp = value;
        },
        vmAccessChage() {
            if (!this.accessVmIp) {
                this.$Message.info('请选择一个IP');
                this.selectDataPanelLoading = false;
                this.$nextTick(() => {
                    this.selectDataPanelLoading = true;
                });
                return;
            }
            let _this = this;
            axios({
                url: 'netns/access/' + this.accessVmId + '/' + this.accessVmType,
                method: 'POST',
                data: {
                    ip: this.accessVmIp
                }
            }).then(function(response) {
                if (response.code == 1) {
                    // var urls = data.attribute.url;
                    _this.accessTokenRef = response.attribute.token;
                    window.openTrain(
                        response.attribute.url +
                            '&Authorization=' +
                            cookieUse.getCookie('desig-token')
                    );
                    _this.selectDataPanelLoading = false;
                    _this.$nextTick(() => {
                        _this.selectDataPanelLoading = true;
                    });
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                    _this.selectDataPanelLoading = false;
                    _this.$nextTick(() => {
                        _this.selectDataPanelLoading = true;
                    });
                }
            });
        },
        controlSearch() {
            if (this.controlSearchBtn) {
                this.controlSearchText = '更多';
                this.controlSearchImage = 'ios-more';
            } else {
                this.controlSearchText = '收起';
                this.controlSearchImage = 'ios-arrow-up';
            }
            this.controlSearchBtn = !this.controlSearchBtn;
        },
        getAccountInfo() {
            let _this = this;
            axios({
                url: '/identity/account/info',
                method: 'get'
            }).then(function(response) {
                if (response.code != '1') {
                    _this.$Message.info(response.message);
                } else {
                    let data = response.data;
                    _this.oUserName = data.nickname;
                    if (data.avatar) {
                        _this.$refs.img_user.src = data.avatar;
                    }
                }
            });
        },
        openPortPanel() {
            this.$refs['formValidate'].resetFields();
            this.openPort = true;
            this.formValidate.type = 'ssh';
            this.formValidate.port = 22;
            this.formValidate.protocol = 'tcp';
            this.disabledType = false;
        },
        addPort() {
            let _this = this;
            this.$refs['formValidate'].validate((valid) => {
                if (valid) {
                    _this.formValidate.type =
                        _this.formValidate.type == 'other'
                            ? _this.formValidate.customType
                            : _this.formValidate.type;
                    axios({
                        url: '/netns/access/' + _this.vmId_ + '/' + _this.formValidate.type,
                        method: 'post',
                        data: {
                            port: _this.formValidate.port,
                            protocal: _this.formValidate.protocol,
                            enablePortForward: true
                        }
                    }).then((response) => {
                        if (response.code == 1) {
                            _this.reachVmPortsList(_this.vmId_);
                            _this.openPort = false;
                            _this.addPortLoading = false;
                            _this.$nextTick(() => {
                                _this.addPortLoading = true;
                            });
                        } else {
                            _this.$Message.error(response.prompt);
                            _this.addPortLoading = false;
                            _this.$nextTick(() => {
                                _this.addPortLoading = true;
                            });
                        }
                    });
                } else {
                    _this.addPortLoading = false;
                    _this.$nextTick(() => {
                        _this.addPortLoading = true;
                    });
                }
            });
        },
        getProjectInformation() {
            let _this = this;
            axios({
                url: 'topo-edit/project/' + _this.currentProjectId
            }).then(function(response) {
                if (response.code == 1) {
                    _this.projectName = response.attribute.project.projectname;
                } else {
                    _this.$Message.error(response.prompt);
                }
            });
        },
        cancel() {},
        SaveMetaData() {
            this.updateVmMetadata(this.vmId_);
        },
        removeMetadata(index) {
            this.metadataData.splice(index, 1);
            console.log(index);
            // alert(index)
        },
        handleAddMetadata() {
            this.metadataData.push({
                key: '',
                value: ''
            });
        },
        switchineVmCurrentPage(currentPage) {
            // console.log(currentPage)
            sessionStorage.setItem('vmCurrentPage', currentPage);
            this.vmCurrentPage = currentPage;
            this.getVmListManage();
            this.selectTableDataGroup = [];
        },
        switchVmItemPage(itemPage) {
            sessionStorage.setItem('vmItemPage', itemPage);
            this.vmItemPage = itemPage;
            this.getVmListManage();
            this.selectTableDataGroup = [];
        },
        getVmListManage() {
            this.refreshIndex = 0;
            let _this = this;
            _this.loadingTable = true;
            let params = {
                projectId: _this.currentProjectId,
                pageIndex: _this.vmCurrentPage,
                pageSize: _this.vmItemPage,
                sortBy: 'name',
                order: 'asc'
            };
            if (_this.virtualNameOfReach) {
                params.name = _this.virtualNameOfReach;
            }
            if (_this.virtualSystypeOfReach) {
                params.sysType = _this.virtualSystypeOfReach;
            }
            if (_this.virtualvmTypeOfReach) {
                params.vmType = _this.virtualvmTypeOfReach;
            }
            if (_this.virtualIPOfReach) {
                params.ipAddress = _this.virtualIPOfReach;
            }
            if (_this.virtualMacOfReach) {
                params.macAddress = _this.virtualMacOfReach;
            }
            if (_this.virtualImageNameOfReach) {
                params.imageName = _this.virtualImageNameOfReach;
            }
            if (_this.virtualNetworkIdOfReach) {
                params.networkId = _this.virtualNetworkIdOfReach;
            }
            axios({
                url: 'topo-edit/deployed/vms',
                method: 'get',
                params: params
            }).then(function(response) {
                if (response.code == 1) {
                    sessionStorage.setItem('vmCurrentPage', _this.vmCurrentPage);
                    _this.vmIdGroupStatus = [];
                    _this.vmTotal = response.data.total;
                    _this.vmListDataTable = response.data.items;
                    // _this.vmListDataTable =  response.data.list.map(item=>{
                    //     item['_loading'] = false;
                    //     return item;
                    // });
                    // // console.log(_this.vmListDataTable)
                    _this.vmIdGroupStatus = response.data.items.map((item) => {
                        return item.id;
                    });
                    // _this.loadingTable = false
                    if (_this.vmIdGroupStatus.length != 0) {
                        _this.reachManyVmStatus(_this.vmIdGroupStatus);
                    }
                    _this.loadingTable = false;
                } else {
                    if (response.code != -2) {
                        _this.$Message.error(response.message);
                    }
                    _this.loadingTable = false;
                }
            });
        },
        vmAccess(vmId, accessType) {
            let _this = this;
            axios({
                url: 'netns/access/' + vmId + '/' + accessType,
                method: 'POST',
                data: {}
            }).then(function(response) {
                if (response.code == 1) {
                    // var urls = data.attribute.url;
                    _this.accessTokenRef = response.attribute.token;
                    window.openTrain(
                        response.attribute.url +
                            '&Authorization=' +
                            cookieUse.getCookie('desig-token')
                    );
                    _this.loadingTable = false;
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                    _this.loadingTable = false;
                }
            });
        },
        //操作网络
        operationVm(vmId, action, batch) {
            let _this = this;
            return axios({
                url: 'topo-control/servers/' + vmId + '/action/' + action,
                method: 'POST'
            }).then((response) => {
                if (response.code == 1) {
                    _this.$Message.info('操作成功');
                    if (batch) {
                        // _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                    } else {
                        _this.reachManyVmStatusSend(_this.vmIdGroupStatus);
                    }
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                }
                _this.vmOpModal.show = false;
            });
        },
        //重置
        rebuildVm(vmId, batch) {
            let _this = this;
            return axios({
                url: 'topo-control/servers/' + vmId + '/action/rebuild',
                method: 'POST'
            }).then((response) => {
                if (response.code == 1) {
                    _this.$Message.info('操作成功');
                    if (batch) {
                        //    _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                    } else {
                        _this.reachManyVmStatusSend(_this.vmIdGroupStatus);
                    }
                } else {
                    _this.$Message.warning({
                        content: response.message,
                        closable: true,
                        duration: 10
                    });
                }
                this.vmOpModal.show = false;
            });
        },
        //重启
        rebootVm(vmId, batch) {
            let _this = this;
            return axios({
                url: 'topo-control/servers/' + vmId + '/action/soft_restart?type=HARD',
                method: 'POST'
            }).then((response) => {
                if (response.code == 1) {
                    _this.$Message.info('操作成功');
                    if (batch) {
                        // _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                    } else {
                        _this.reachManyVmStatusSend(_this.vmIdGroupStatus);
                    }
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                }
                this.vmOpModal.show = false;
            });
        },
        vmSwitchTypeOp(id, type) {
            let vmId = id || this.opVm.id;
            let text = type || this.opVmType;
            let batch = '';
            let _this = this;
            switch (text) {
                case '关机':
                    _this.operationVm(vmId, 'stop', batch);
                    break;
                case '开机':
                    _this.operationVm(vmId, 'start', batch);
                    break;
                case '重置状态':
                    _this.operationVm(vmId, 'reset-state-active', batch);
                    break;
                case '重启':
                    _this.rebootVm(vmId, batch);
                    break;
                case '重置':
                    _this.rebuildVm(vmId, batch);
                    break;
                case '挂起':
                    _this.operationVm(vmId, 'suspend', batch);
                    break;
                case '暂停':
                    _this.operationVm(vmId, 'pause', batch);
                    break;
                case '拯救':
                    _this.operationVm(vmId, 'resume', batch);
                    break;
                case '取消暂停':
                    _this.operationVm(vmId, 'unpause', batch);
                    break;
            }
        },
        vmSwitchTypeOperation(vmId, text, params = '', batch = '') {
            let _this = this;
            switch (text) {
                case '关机':
                    _this.operationVm(vmId, 'stop', batch);
                    break;
                case '开机':
                    _this.operationVm(vmId, 'start', batch);
                    break;
                case '重置状态':
                    _this.operationVm(vmId, 'reset-state-active', batch);
                    break;
                case '重启':
                    _this.rebootVm(vmId, batch);
                    break;
                case '重置':
                    _this.rebuildVm(vmId, batch);
                    break;
                case '挂起':
                    _this.operationVm(vmId, 'suspend', batch);
                    break;
                case '暂停':
                    _this.operationVm(vmId, 'pause', batch);
                    break;
                case '拯救':
                    _this.operationVm(vmId, 'resume', batch);
                    break;
                case '取消暂停':
                    _this.operationVm(vmId, 'unpause', batch);
                    break;
                case '密码':
                    _this.vmId_ = params.id;
                    _this.vmPassword = '';
                    _this.passwordModal.show = true;
                    return;
                case '元数据':
                    _this.vmMetadata = true;

                    _this.metadataData = [
                        {
                            key: '',
                            value: ''
                        }
                    ];
                    _this.reachVmMetaData(params.id);
                    _this.vmName = params.name;
                    _this.vmId_ = params.id;
                    break;
                case '端口转发':
                    _this.vmName = params.name;
                    _this.vmId_ = params.id;
                    _this.portTableData = [];
                    _this.portListPanel = true;
                    _this.reachVmPortsList(params.id);
                    break;
                default:
                    console.log('不识别命令：' + text);
                    break;
            }
        },
        //查询虚拟机的状态
        reachVmStatus(vmId) {
            let _this = this;
            axios({
                url: 'topo-control/servers/' + vmId + '/status'
            }).then(function(response) {
                if (response.code == 1) {
                    if (response.list[0].taskStatus != 'null') {
                        _this.reachVmStatus(vmId);
                    } else {
                        _this.getVmListManage();
                        // var status = response.list[0].status;
                    }
                } else {
                    if (response.message) {
                        _this.$Message.error({
                            content: response.message,
                            closable: true,
                            duration: 10
                        });
                    } else {
                        _this.$Message.error({
                            content: response.prompt,
                            closable: true,
                            duration: 10
                        });
                    }
                }
            });
        },
        //批量查询虚拟机状态
        reachManyVmStatus(vmIdGroup) {
            let _this = this;
            axios({
                url: 'topo-control/servers/batch_status',
                method: 'POST',
                data: vmIdGroup
            }).then(function(response) {
                if (response.code == 1) {
                    let status_null = [];
                    let vm_status = '',
                        vm_loading = false;
                    _this.vmGroupStatus = response.list.map((item) => {
                        if (item.taskStatus != 'null') {
                            status_null.push(item.vmId);
                            vm_status = item.taskStatus;
                            vm_loading = true;
                        } else {
                            vm_status = item.status;
                            vm_loading = false;
                        }
                        return {
                            id: item.vmId,
                            status: vm_status,
                            loading: vm_loading,
                            enableCrash: item.enableCrash,
                            crashMsg: item.crashMsg ? item.crashMsg : ''
                        };
                    });
                    if (status_null.length != 0) {
                        console.log(status_null);
                        _this.reachManyVmStatusSend(status_null);
                    }
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                }
            });
        },
        reachManyVmStatusSend(vmIdGroup) {
            // console.log('----');
            let _this = this;
            clearTimeout(_this.setTimeClear);
            axios({
                url: 'topo-control/servers/batch_status',
                method: 'POST',
                data: vmIdGroup
            }).then(function(response) {
                if (response.code == 1) {
                    let status_null = [];
                    let status_new = [];
                    let vm_status = '';
                    status_new = response.list.map((item) => {
                        if (item.taskStatus != 'null') {
                            status_null.push(item.vmId);
                            vm_status = item.taskStatus;
                        } else {
                            vm_status = item.status;
                        }
                        return {
                            id: item.vmId,
                            status: vm_status
                        };
                    });
                    _this.vmGroupStatus.forEach((item) => {
                        status_new.forEach((element) => {
                            if (item.id == element.id) {
                                item.status = element.status;
                            }
                        });
                    });
                    if (status_null.length != 0) {
                        _this.setTimeClear = setTimeout(() => {
                            _this.reachManyVmStatusSend(status_null);
                        }, 3000);
                    }
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                }
            });
        },
        updatePassword(vmId, btnLoading) {
            let _this = this;
            if (!_this.vmPassword) {
                _this.$Message.info('请输入密码');
                btnLoading = false;
                return;
            }
            axios({
                url: `topo-control/servers/${vmId}/admin-password?password=${_this.vmPassword}`,
                method: 'put'
            }).then(function(response) {
                if (response.code == 1) {
                    _this.$Message.success('编辑成功');
                    _this.getVmListManage();
                    _this.$Modal.remove();
                    _this.updatePasswordLoading = false;
                    _this.$nextTick(() => {
                        _this.updatePasswordLoading = true;
                    });
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                    btnLoading = false;
                    _this.$nextTick(() => {
                        btnLoading = true;
                    });
                }
            });
        },
        //批量编辑生成随机密码
        updateVmPasswordMany(vmId) {
            let _this = this;
            return axios({
                url: 'remote/changePassword/' + vmId + '?password=' + _this.getRandomPassword(6)
            }).then(function(response) {
                if (response.code == 1) {
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                }
            });
        },
        getRandomPassword(range) {
            let str = '',
                arr = [
                    'a',
                    'b',
                    'c',
                    'd',
                    'e',
                    'f',
                    'g',
                    'h',
                    'i',
                    'j',
                    'k',
                    'l',
                    'm',
                    'n',
                    'o',
                    'p',
                    'q',
                    'r',
                    's',
                    't',
                    'u',
                    'v',
                    'w',
                    'x',
                    'y',
                    'z',
                    'A',
                    'B',
                    'C',
                    'D',
                    'E',
                    'F',
                    'G',
                    'H',
                    'I',
                    'J',
                    'K',
                    'L',
                    'M',
                    'N',
                    'O',
                    'P',
                    'Q',
                    'R',
                    'S',
                    'T',
                    'U',
                    'V',
                    'W',
                    'X',
                    'Y',
                    'Z',
                    '0',
                    '1',
                    '2',
                    '3',
                    '4',
                    '5',
                    '6',
                    '7',
                    '8',
                    '9'
                ];
            for (let i = 0; i < range; i++) {
                let pos = Math.round(Math.random() * (arr.length - 1));
                str += arr[pos];
            }
            return str;
        },
        reachVmMetaData(vmId) {
            let _this = this;
            axios({
                url: 'topo-control/servers/' + vmId + '/metadata',
                method: 'get'
            }).then(function(response) {
                if (response.code == 1) {
                    _this.metadataData = [];
                    let metadata_ = response.attribute.metadata;
                    if (JSON.stringify(metadata_) == '{}') {
                        _this.metadataData.push({
                            key: '',
                            value: ''
                        });
                    } else {
                        for (let i in metadata_) {
                            _this.metadataData.push({
                                key: i,
                                value: metadata_[i]
                            });
                        }
                    }
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        duration: 10,
                        closable: true
                    });
                }
            });
        },
        updateVmMetadata(vmId) {
            let _this = this;
            let objMedata = {};
            _this.metadataData.forEach((element) => {
                objMedata[element.key] = element.value;
            });
            axios({
                url: 'topo-control/servers/' + vmId + '/metadata',
                method: 'put',
                data: objMedata
            }).then(function(response) {
                if (response.code == 1) {
                    _this.$Message.success('保存成功');
                    _this.vmMetadata = false;
                    _this.vmMetadataLoading = false;
                    _this.$nextTick(() => {
                        _this.vmMetadataLoading = true;
                    });
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                    _this.vmMetadataLoading = false;
                    _this.$nextTick(() => {
                        _this.vmMetadataLoading = true;
                    });
                }
            });
        },
        deleteVmMetadata(vmId, key) {
            let _this = this;
            axios({
                url: 'topo-control/servers/' + vmId + '/metadata/' + key,
                method: 'delete'
            }).then(function(response) {
                if (response.code == 1) {
                    // _this.
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                }
            });
        },
        //查询虚拟机的key
        getVmAttributeKey(value) {
            if (!value) {
                return;
            }
            let _this = this;
            axios({
                url: 'topo-edit/topo/' + _this.currentProjectId + '/attribute/tree?type=VM'
            }).then(function(response) {
                if (response.code == 1) {
                    if (response.attribute.result != '{}') {
                        _this.vmAttributeData = Object.keys(response.attribute.result).map(
                            (item) => {
                                let oneMenu = [
                                    {
                                        label: '--',
                                        value: '--'
                                    }
                                ];
                                return {
                                    value: item,
                                    label: 'key：' + item,
                                    children: oneMenu
                                };
                            }
                        );
                        console.log(_this.vmKeys);
                    }
                } else {
                    if (response.code != -2) {
                        _this.$Message.error({
                            content: response.prompt,
                            closable: true,
                            duration: 10
                        });
                    }
                }
            });
        },
        //通过key 查找value
        getValueByVmKey(vmAttributeKey) {
            console.log(vmAttributeKey);
            let _this = this;
            _this.vmValues = [];
            _this.virtualValueOfReach = '';
            if (!vmAttributeKey) {
                return;
            }
            axios({
                url: 'topo-edit/topo/' + _this.currentProjectId + '/attribute/key/' + vmAttributeKey
            }).then(function(response) {
                if (response.code == 1) {
                    if (response.attribute.result.length != 0) {
                        _this.vmValues = response.attribute.result;
                    }
                } else {
                    _this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10
                    });
                }
            });
        },
        listenKeyChange(vmAttributeKey) {
            console.log(vmAttributeKey);
            let _this = this;
            if (!vmAttributeKey) {
                _this.virtualKeyOfReach = '';
                _this.virtualValueOfReach = '';
                return;
            } else {
                if (vmAttributeKey.length == 1) {
                    _this.virtualKeyOfReach = vmAttributeKey[0];
                    _this.virtualValueOfReach = '';
                    axios({
                        url:
                            'topo-edit/topo/' +
                            _this.currentProjectId +
                            '/attribute/key/' +
                            vmAttributeKey[0]
                    }).then(function(response) {
                        if (response.code == 1) {
                            if (response.attribute.result.length != 0) {
                                // _this.vmValues = response.attribute.result;
                                for (let i = 0; i < _this.vmAttributeData.length; i++) {
                                    if (_this.vmAttributeData[i].value == vmAttributeKey[0]) {
                                        _this.vmAttributeData[i].children = [];
                                        response.attribute.result.forEach((element) => {
                                            _this.vmAttributeData[i].children.push({
                                                label: 'value：' + element,
                                                value: element
                                            });
                                        });
                                        return;
                                    }
                                }
                            }
                        } else {
                            _this.$Message.error({
                                content: response.prompt,
                                closable: true,
                                duration: 10
                            });
                        }
                    });
                } else {
                    _this.virtualKeyOfReach = vmAttributeKey[0];
                    _this.virtualValueOfReach = vmAttributeKey[1];
                }
            }
            _this.vmCurrentPage = 1;
            sessionStorage.setItem('vmCurrentPage', 1);
            _this.getVmListManage();
        },
        opeartionManyVm() {
            let _this = this;
            if (this.selectTableDataGroup.length != 0) {
                // _this.isSpinShow = true
                _this.loadingTable = true;
                // let vmGroupStatus = this.selectTableDataGroup.map(item=>{
                //     return item.status;
                // });
                let vmGroupStatus = [];
                axios({
                    url: 'topo-control/servers/batch_status',
                    method: 'POST',
                    data: _this.selectTableDataGroup.map((item) => {
                        return item.id;
                    })
                })
                    .then(function(response) {
                        if (response.code == 1) {
                            let vm_status = '';
                            return (vmGroupStatus = response.list.map((item) => {
                                if (item.taskStatus != 'null') {
                                    vm_status = item.taskStatus;
                                } else {
                                    vm_status = item.status;
                                }
                                return vm_status;
                            }));
                        } else {
                            _this.loadingTable = false;
                            _this.$Message.error({
                                content: response.prompt,
                                closable: true,
                                duration: 10
                            });
                        }
                    })
                    .then(function(vmGroupStatus) {
                        _this.vmManyNumber = vmGroupStatus.length;
                        // vmGroupStatus = new Set(vmGroupStatus);
                        let uniqueArr = [...new Set(vmGroupStatus)];
                        _this.loadingTable = false;
                        if (uniqueArr.length != 1) {
                            _this.$Message.info('您选择的虚拟机中，存在不同状态的虚拟机');
                        } else {
                            _this.vmManyPanel = true;
                            // console.log(uniqueArr[0])
                            switch (uniqueArr[0]) {
                                case 'ACTIVE':
                                    _this.btnData = [
                                        '关机',
                                        '重启',
                                        '重置',
                                        '挂起',
                                        '暂停',
                                        '编辑密码(系统随机生成)'
                                    ];
                                    break;
                                case 'Running':
                                    _this.btnData = [
                                        '关机',
                                        '重启',
                                        '重置',
                                        '挂起',
                                        '暂停',
                                        '编辑密码(系统随机生成)'
                                    ];
                                    break;
                                case 'SHUTOFF':
                                    _this.btnData = ['开机', '重置'];
                                    break;
                                case 'DOWN':
                                    _this.btnData = ['开机', '重置'];
                                    break;
                                case 'Stopped':
                                    _this.btnData = ['开机', '重置'];
                                    break;
                                case 'SUSPENDED':
                                    _this.btnData = ['拯救'];
                                    break;
                                case 'ERROR':
                                    _this.btnData = ['重启', '重置状态'];
                                    break;
                                case 'PAUSED':
                                    _this.btnData = ['取消暂停'];
                                    break;
                                case 'CRUSH': //虚拟机奔溃状态
                                    _this.btnData = ['关机', '重启'];
                                    break;
                                case 'UNKNOWN': //虚拟机未知状态
                                    _this.btnData = [];
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
            } else {
                _this.$Message.info('请选择要操作的虚拟机');
            }
        },
        selectTableData(values) {
            this.selectTableDataGroup = values;
            // console.log(values)
        },
        testFgm(value) {
            this.selectTableDataGroup.forEach((element) => {
                this.vmSwitchTypeOperation(element.id, value, '', true);
            });
        },
        okVm(value) {
            let _this = this;
            let activeFunction = [];
            activeFunction = this.selectTableDataGroup.map((element) => {
                let vmId = element.id;
                let batch = true;
                return new Promise((resolve, reject) => {
                    switch (value) {
                        case '关机':
                            _this.operationVm(vmId, 'stop', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '开机':
                            _this.operationVm(vmId, 'start', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '重启':
                            _this.rebootVm(vmId, batch).then(() => {
                                resolve();
                            });
                            break;
                        case '重置':
                            _this.rebuildVm(vmId, batch).then(() => {
                                resolve();
                            });
                            break;
                        case '挂起':
                            _this.operationVm(vmId, 'suspend', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '暂停':
                            _this.operationVm(vmId, 'pause', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '拯救':
                            _this.operationVm(vmId, 'resume', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '取消暂停':
                            _this.operationVm(vmId, 'unpause', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '编辑密码(系统随机生成)':
                            _this.updateVmPasswordMany(vmId).then(() => {
                                resolve();
                            });
                            break;
                        default:
                            break;
                    }
                });
            });
            console.log(activeFunction);
            this.vmManyPanel = false;
            Promise.all(activeFunction).then(() => {
                _this.getVmListManage();
            });
            return;
        },
        test(value) {
            // console.log(value)
        },
        reachVmPortsList(vmId) {
            let _this = this;
            _this.portTableData = [];
            return axios({
                url: 'netns/access/detail?vmId=' + vmId,
                method: 'get'
                // params:{
                //     vmId:vmId
                // }
            }).then((response) => {
                if (response.code == 1) {
                    // return response.attribute.result
                    $.each(response.attribute.result.pageData, function(i, item) {
                        if (item.forwardIp) {
                            _this.portTableData.push(item);
                        }
                    });
                    // _this.portTableData = response.attribute.result.pageData.filter((item)=>{
                    //     return item.forwardIP;
                    // });
                } else if (response.code == -2) {
                    _this.portTableData = [];
                } else {
                    _this.$Message.error(response.prompt);
                }
            });
        },
        deleteVmPort(token) {
            let _this = this;
            axios({
                url: '/netns/access/tokens/' + token,
                method: 'delete'
            }).then((response) => {
                if (response.code == 1) {
                    _this.reachVmPortsList(this.vmId_);
                } else {
                    _this.$Message.error(response.prompt);
                }
            });
        },
        listenTypeChange(value) {
            console.log(value);
            let _this = this;
            _this.disabledprototol = true;
            _this.disabledType = true;
            switch (value) {
                case 'ssh':
                    _this.formValidate.port = 22;
                    _this.formValidate.protocol = 'tcp';
                    _this.disabledType = false;
                    _this.formValidate.customType = 'test';
                    break;
                case 'rdp':
                    _this.formValidate.port = 3389;
                    _this.formValidate.protocol = 'tcp';
                    _this.disabledType = false;
                    _this.formValidate.customType = 'test';
                    break;
                case 'vnc':
                    _this.formValidate.port = 5901;
                    _this.formValidate.protocol = 'tcp';
                    _this.disabledType = false;
                    _this.formValidate.customType = 'test';
                    break;
                case 'other':
                    // _this.formValidate.port = 22
                    _this.disabledprototol = false;
                    _this.disabledType = true;
                    _this.formValidate.port = 1;
                    _this.formValidate.customType = '';
                    break;
                default:
                    break;
            }
        },
        deleteAccessAisle(vmId) {
            let _this = this;
            axios({
                url: 'netns/access/vms/' + vmId,
                method: 'delete'
            }).then((response) => {
                if (response.code == 1) {
                    _this.$Message.success('刷新成功');
                    _this.loadingTable = false;
                } else {
                    _this.$Message.success(response.prompt);
                    _this.loadingTable = false;
                }
            });
        },
        limitingReach() {
            let _this = this;
            clearTimeout(_this.setTimeoutReach);
            _this.setTimeoutReach = setTimeout(() => {
                _this.getVmListManage();
            }, 500);
        },
        reachNetworkList(value) {
            if (!value) {
                return;
            }
            let _this = this;
            axios({
                url: 'topo-edit/topo/project/' + _this.currentProjectId + '/tree',
                method: 'GET',
                data: 'NW'
            }).then(function(response) {
                if (response.code == 1) {
                    _this.networkData = [];
                    let networkDataTree = response.data;
                    function getNetwork(currentNetworkData) {
                        _this.networkData.push({
                            networkName: currentNetworkData.name,
                            networkId: currentNetworkData.id
                        });
                        if (
                            currentNetworkData.networks &&
                            currentNetworkData.networks.length != 0
                        ) {
                            for (let i = 0; i < currentNetworkData.networks.length; i++) {
                                getNetwork(currentNetworkData.networks[i]);
                            }
                        }
                    }
                    getNetwork(networkDataTree);
                    console.log(_this.networkData);
                } else {
                    _this.$Message.error(response.prompt);
                }
            });
        },
        reachSubnetList(value) {
            if (!value) {
                return;
            }
            let _this = this;
            axios({
                //              url:'deploy/project/subnets?projectId='+_this.currentProjectId+'&page=1&rows=20000',
                url:
                    `topo-edit/deployed/projects/${_this.currentProjectId}/subnets` +
                    '&pageIndex=1&pageSize=20000',
                method: 'GET'
            }).then(function(response) {
                if (response.code == 1) {
                    _this.subnetData = response.data.items;
                } else {
                    _this.$Message.error(response.prompt);
                }
            });
        },
        reachSegmentList(value) {
            console.log(value);
            if (!value) {
                return;
            }
            let _this = this;
            axios({
                //              url:'deploy/project/segments?projectId='+_this.currentProjectId+'&page=1&rows=20000',
                url:
                    `topo-edit/deployed/projects/${_this.currentProjectId}/segments` +
                    '&pageIndex=1&pageSize=20000',
                method: 'GET'
            }).then(function(response) {
                if (response.code == 1) {
                    _this.segmentsData = response.data.items;
                } else {
                    _this.$Message.error(response.prompt);
                }
            });
        },
        changePassword() {
            let _this = this;
            if (!_this.vmPassword) {
                _this.$Message.info('请填写密码');
                _this.loading = false;
                _this.passwordModal.loading = false;
                setTimeout(() => {
                    _this.passwordModal.loading = true;
                }, 500);
                return;
            }
            axios({
                //              url:'remote/changePassword/'+_this.vmId_+'?password='+_this.vmPassword,
                url: `topo-control/servers/${_this.vmId_}/admin-password?pwd=${_this.vmPassword}`,
                method: 'put'
            })
                .then(function(response) {
                    if (response.code == 1) {
                        _this.$Message.success('编辑成功');
                        _this.getVmListManage();
                        _this.passwordModal.show = false;
                        // _this.$Modal.remove()
                        // _this.updatePasswordLoading = false;
                        // _this.$nextTick(()=>{
                        //     _this.updatePasswordLoading = true;
                        // })
                    } else {
                        _this.$Message.error({
                            content: response.prompt,
                            closable: true,
                            duration: 10
                        });
                        // _this.updatePasswordLoading = false;
                        // _this.$nextTick(()=>{
                        //     _this.updatePasswordLoading = true;
                        // })
                    }
                    _this.passwordModal.loading = false;
                    setTimeout(() => {
                        _this.passwordModal.loading = true;
                    }, 500);
                })
                .catch((error) => {
                    _this.passwordModal.loading = false;
                    setTimeout(() => {
                        _this.passwordModal.loading = true;
                    }, 500);
                    console.log(error);
                });
        },
        createImage(curVm) {
            axios({
                url: `quickexp/replaceImage/create`,
                method: 'post',
                data: {
                    cloudId: curVm.cloudId,
                    ecId: this.caseId,
                    ecName: this.caseName,
                    imageId: curVm.imageId,
                    projectId: this.prjId,
                    templId: this.templateId,
                    vmId: curVm.id,
                    vmName: curVm.name
                }
            })
                .then((response) => {
                    if (response.code == 1) {
                        this.$Message.success(response.message);
                        this.$emit('setImageList');
                    } else {
                        this.$Message.error({
                            content: response.message,
                            closable: true,
                            duration: 10
                        });
                    }
                    this.createImageModal.loading = false;
                    setTimeout(() => {
                        this.createImageModal.loading = true;
                    }, 500);
                })
                .catch((error) => {
                    console.log(error);
                    this.$Message.error('服务器连接失败，请稍后再试');
                    this.createImageModal.loading = false;
                    setTimeout(() => {
                        this.createImageModal.loading = true;
                    }, 500);
                });
        }
    },
    beforeCreate() {},
    beforeMount() {},
    mounted() {},
    beforeUpdate() {},
    beforeDestroy() {},
    destroyed() {},
    watch: {}
};
</script>

<style>
.access-name {
    color: #db4747;
    margin-left: 20px;
}
.headerBtn1 {
    text-align: left;
    margin: 15px 0;
}
.pageStyle1 {
    text-align: center;
    margin-top: 10px;
}
.status-loading.ivu-btn:before {
    background: none;
}
.status-loading .ivu-load-loop {
    font-weight: bold;
}
.operation .ivu-select-arrow {
    right: 2px;
}
.operation .ivu-select-selection {
    border-radius: 0px 4px 4px 0px;
}
.accessType .ivu-select-arrow {
    right: 2px;
}
.accessType .ivu-select-selection {
    border-radius: 0px 4px 4px 0px;
}
.opertionVm .ivu-select-arrow {
    right: 2px;
}
.opertionVm .ivu-select-selection {
    border-radius: 0px 4px 4px 0px;
}
.ivu-table-wrapper {
    /*overflow: visible !important*/
}
.ivu-tag-border.ivu-tag-closable .ivu-icon-ios-close {
    top: -2px;
}
.ivu-table-tip {
    overflow: hidden !important;
}

.expendSpanStyle {
    display: inline-block;
    margin-right: 25px;
    min-width: 300px;
}

#vmListTable .ivu-table-overflowX {
    overflow: auto;
}
#vmListTable::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 6px;
}
#vmListTable::-webkit-scrollbar-thumb {
    /*滚动条里面小方块样式*/
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(209, 209, 209, 0.6);
}
#vmListTable::-webkit-scrollbar-track {
    /*滚动条里面轨道样式*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 5px;
    background: rgba(179, 179, 179, 0.1);
}

/* .demo-spin-icon-load{
    animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
   from { transform: rotate(0deg);}
   50% { transform: rotate(180deg);}
   to { transform: rotate(360deg);}
} */
/* 假如内容过长，一屏放不下，滚动条下拉覆盖不全 */
/* .ivu-spin-fix {
    position: fixed;
} */
</style>
